rm(list=ls())
# Set working directory
setwd("")

# Initialize stuff
theta.median <- theta.true <- theta.iqr <- theta.madm <- matrix(0, 6, 4)
sc.diff.small <- sc.diff.large <- matrix(0, 5, 4)
rlnm <- c("Log", "Brier", "Spherical", "Boosting", "As1", "As2")

# Function for median absolute deviation from median
madm <- function(x){
  m <- median(x)
  median(abs(x-m))
}

# Loop over DGPs
for (dgp.nr in 1:4){

  # Load workspace (produced via file "MCstudy_rollingwindows.R")
  load(paste0("rwMC_dgp", dgp.nr, "_120_10000.RData"))
  
  # Load true parameters
  theta.true[, dgp.nr] <- as.numeric(readLines(paste0("thetas", dgp.nr, "_1e+06.csv")))
  
  # Unlist theta
  theta.all <- sapply(1:6, function(j) sapply(pars, function(s) s[, j]))
  
  # Compute summary statistics
  theta.median[, dgp.nr] <- apply(theta.all, 2, median)
  theta.iqr[, dgp.nr] <- apply(theta.all, 2, function(s) quantile(s, 0.9) - quantile(s, 0.1))
  theta.madm[, dgp.nr] <- apply(theta.all, 2, madm)
  sc.diff.small[, dgp.nr] <- colMeans(sc.small > 0)
  sc.diff.large[, dgp.nr] <- colMeans(sc.large > 0)
  
  # Clear part of the workspace
  rm(list = setdiff(ls(), c("pars", "dgp.nr", "theta.true", "theta.iqr", "theta.madm", "theta.median", "madm", "rlnm", "sc.diff.small", "sc.diff.large")))
}

# Write summary statistics to a format that can be loaded into a tex file
writeLines(paste(rlnm, "&&", apply(round(theta.median, 2), 1, function(s) paste(s, collapse = "&")), "\\\\"), 
           "theta_median.txt")
writeLines(paste(rlnm, "&&", apply(round(theta.iqr, 2), 1, function(s) paste(s, collapse = "&")), "\\\\"), 
           "theta_iqr.txt")
writeLines(paste(rlnm, "&&", apply(round(theta.madm, 2), 1, function(s) paste(s, collapse = "&")), "\\\\"), 
           "theta_madm.txt")
writeLines(paste(rlnm, "&&", apply(round(theta.true, 2), 1, function(s) paste(s, collapse = "&")), "\\\\"), 
           "theta_true.txt")
writeLines(paste(rlnm[-1], "&&", apply(round(sc.diff.small, 2), 1, function(s) paste(s, collapse = "&")), "\\\\"), 
           "sc_diff_small.txt")
writeLines(paste(rlnm[-1], "&&", apply(round(sc.diff.large, 2), 1, function(s) paste(s, collapse = "&")), "\\\\"), 
           "sc_diff_large.txt")